<?php
// +----------------------------------------------------------------------
// | Title   : 首页接口
// +----------------------------------------------------------------------
// | Created : Henrick (me@hejinmin.cn)
// +----------------------------------------------------------------------
// | From    : Shenzhen wepartner network Ltd
// +----------------------------------------------------------------------
// | Date    : 2017/5/23 09:14
// +----------------------------------------------------------------------
namespace app\apiv1\controller;
use \app\core\Apicontroller;
use think\Db;

/**
 * Class 首页接口
 * @package app\apiv1\controller
 */
class Home extends Apicontroller{

    function index(){
        $this->_err();
    }

    function wxUserCode(){ //通过code换取session_key
        $req = request();
        $code = $req->post('code');
        if(!$code){
            $this->error(1,'缺省参数');
        }
        $wechat_app = config('wechat_app');
        $url = sprintf($wechat_app['http_session_key'],$wechat_app['appid'],$wechat_app['appsecret'],$code);
        $res = http($url);
        $res = json_decode($res,true);
        if(!isset($res['session_key'])){
            $this->_err(1,'签名失败，参数有误');
        }
        //查询用户是否存在
        $user_wechat = model('userWechatApp');
        $user_wechat_res = $user_wechat->where(['openid'=>$res['openid'],'row_status'=>'0'])->find();
        if(isset($user_wechat_res->id)){
            $user_wechat_res = $user_wechat_res->toArray();
        }
        $time = time();
        $session_3rd = $user_wechat_res['session_3rd'];
        $open_id = $res['openid'];
        if(!isset($user_wechat_res['id']) || !$user_wechat_res['id']){
            //创建用户信息
            $data = array(
                'openid'      => $open_id,
                'session_key' => $res['session_key'],
                'session_3rd' => md5($res['session_key'].$wechat_app['appid'].$time),
                'create_time' => date("Y-m-d H:i:s")
            );
            $res = $user_wechat->insert($data);
            if(!$res){
                $this->_err(1,'数据插件失败！');
            }
            $session_3rd = $data['session_3rd'];
        }else{
            //创建用户信息
            $data = array(
                'openid'      => $open_id,
                'session_key' => $res['session_key'],
                'session_3rd' => md5($res['session_key'].$wechat_app['appid'].$time),
                'update_time' => date("Y-m-d H:i:s")
            );
            $res = $user_wechat->update($data,['id'=>$user_wechat_res['id']]);
            if(!$res){
                $this->_err(1,'数据更新失败！');
            }
            $session_3rd = $data['session_3rd'];
        }

        cache($session_3rd,['user_id'=>$user_wechat_res['user_id'],'openid'=>$open_id,'time'=>$time+7100,'session_key'=>$data['session_key']]);

        $this->_err(0,'ok',['session_3rd'=>$session_3rd,'time'=>$time]);
    }

    function userLogin(){  // 微信用户授权登录
        $req = request();
        $post = $req->post();
        $wechat = cache($this->token);
        $sign = sha1($post['rawData'].$wechat['session_key']);
        if($sign!==$post['signature']){
            $this->_err(1,'微信签名不正确！');
        }

        $wechat_app = config('wechat_app');
        vendor('wechat.wxBizDataCrypt');
        $pc = new \WXBizDataCrypt($wechat_app['appid'], $wechat['session_key']);
        $errCode = $pc->decryptData($post['encryptedData'], $post['iv'], $data );
        if($errCode){
            $this->_err(1,'非法数据');
        }
        $userInfo = json_decode($data,true);
        if(!$wechat['user_id']){ //判断用户是否存在,
            $salt = randCode(15);
            Db::startTrans();
            //注册用户
            $data = [
                'user_name' => $wechat['openid'],
                'pass_word' => md5(md5($wechat['openid'].$salt)),
                'salt'      => $salt,
                'nick_name' => base64_encode($userInfo['nickName']),
                'avatar'    => $userInfo['avatarUrl'],
                'reg_time'  => date("Y-m-d H:i:s"),
                'from_org'  => '2',
                'create_time' => date("Y-m-d H:i:s")
            ];
            $user = model('user');
            $user_res = $user->save($data);
            if(!$user_res){
                Db::rollback();
                $this->_err(1,'用户注册失败');
            }
            $id = $user->getLastInsID();
            $wechat_user = model('userWechatApp');
            $update_data = [
                'user_id' => $id
            ];
            $res = $wechat_user->update($update_data,['openid'=>$wechat['openid']]);
            if(!$res){
                Db::rollback();
                $this->_err(1,'用户更新失败');
            }
            Db::commit();
            $wechat['user_id']   = $id;
            $data['nick_name'] = base64_decode($data['nick_name']);
            $wechat['user_info'] = $data;
            cache($this->token,$wechat);
        }else{
            $wechat_user = model('userWechatApp');
            $user_info = $wechat_user->field('user_name,nick_name,avatar,reg_time')->where(['id'=>$wechat['user_id']])->find()->toArray();
            $user_info['nick_name'] = base64_decode($user_info['nick_name']);
            $wechat['user_info'] = $user_info;
            cache($this->token,$wechat);
        }
        $this->_err(0,'登录成功');
    }
}